import os

from tornado import web, ioloop

from util.web.stop_server import StopServerHandler
from handler import MyAPIHandler
from util import json, db
from business import Business
import logging
import sys

# 使用 bat 脚本启动需要设置 sources root
file_path = os.path.split(os.path.realpath(__file__))[0]
obj_path = os.path.abspath(os.path.dirname(file_path) + os.path.sep + "algorithm" + os.sep + "ai")
sys.path.append(obj_path)


def get_config(path, encoding='utf-8'):
    config = json.json_file2obj(path, encoding=encoding)
    version = config.version if 'version' in config else 1
    if version < 2:
        old_ver = version
        while version < 2:
            config = upgrade_to_version_2(config)
            version += 1
        rename(path, old_ver)
        json.obj2json_file(config, path, encoding=encoding)
    return config


def rename(path, old_ver):
    pos = path.rfind('.')
    if pos < 0:
        pos = len(path)
    new_path = path[:pos] + ('_%s_old' % old_ver) + path[pos:]
    os.rename(path, new_path)


def upgrade_to_version_2(config):
    with db.DBManager(config.db) as dbm:
        sql = "ALTER TABLE distributes ADD COLUMN `camera_id` SMALLINT NOT NULL COMMENT '整型的照相机id'"
        dbm.execute(sql)

    config.version = 2
    images = config.images
    config.duration_seconds = images.duration_seconds
    config.images_name_pattern = images.name_pattern
    config.images_root = images.root
    del images.duration_seconds
    del images.name_pattern
    del images.root
    images.id = 1
    images.name = "NoName"
    config.cameras = [images]
    del config.images

    return config


if __name__ == '__main__':
    config = get_config('config/config.json')
    business = Business()
    business.set_config(config)
    config.business = business
    business.start()

    app = web.Application([
        ('/api/(.*)', MyAPIHandler, {'api_package': 'api', 'business': business}),
        ('/stop/server', StopServerHandler, {'password': config.stop_password}),
        ('/static/(.*)', web.StaticFileHandler, {'path': './static'}),
        ('/(.*)', web.StaticFileHandler, {'path': './static', 'default_filename': 'index.html'}),
    ])

    app.listen(config.port)
    print('The server V2 on port %d is started!' % config.port)
    ioloop.IOLoop.current().start()
    business.stop()
    print('The server on port %d is stopped!' % config.port)
